/* 2016/2/21 */
package com.cosmos.pictureswitcher;

import android.Manifest;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Messenger;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.cosmos.pictureswitcher.io.FileUtil;
import com.cosmos.pictureswitcher.io.UriParser;
import com.cosmos.pictureswitcher.service.ServiceUtil;
import com.cosmos.pictureswitcher.wallpaper.SwitchWallpaperService;

import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity implements ListNameFragment.OnNewListNameListener {
    private static final String LOG_TAG = MainActivity.class.getSimpleName();

    private static final String CHOOSE_FILE_TYPE = "*/*";
    private static final int REQUEST_CODE_SELECT_PICTURE = 1;
    private static final int REQUEST_CODE_PERMISSION_WRITE_EXTERNAL_STORAGE = 1;

    private static final int COPY_FILE_BUFFER_LENGTH = 0x400;

    private static final String FRAGMENT_TAG_LIST_NAME = "list_name";
    private static final String DEFAULT_LIST_NAME = "Default";

    private ImageSwitcher imageSwitcher;
    private LinearLayout pictureLinearLayout;

    /**
     * ID of selected picture.
     */
    private int currentPosition;
    /**
     * X axis of touch point.
     */
    private float downX;

    /** Messenger for communicating with the service. */
    private Messenger serviceMessenger = null;
    /** Flag indicating whether bind is called on the service. */
    private boolean isBound;
    /**
     * Class for interacting with the main interface of the service.
     */
    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            // This is called when the connection with the service has been
            // established, giving us the object we can use to
            // interact with the service.  We are communicating with the
            // service using a Messenger, so here we get a client-side
            // representation of that from the raw IBinder object.
            serviceMessenger = new Messenger(service);
            isBound = true;
        }

        public void onServiceDisconnected(ComponentName className) {
            // This is called when the connection with the service has been
            // unexpectedly disconnected -- that is, its process crashed.
            serviceMessenger = null;
            isBound = false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                /*ListNameFragment listNameDialog = new ListNameFragment();
                listNameDialog.setCreateMode();
                listNameDialog.show(getFragmentManager(), FRAGMENT_TAG__LIST_NAME);*/
                addPicture();
            }
        });

        /*imageSwitcher = (ImageSwitcher) findViewById(R.id.imageSwitcher);
        imageSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
            @Override
            public View makeView() {
                ImageView imageView = new ImageView(MainActivity.this);
                imageView.setBackgroundColor(0xFF000000);
                imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
                imageView.setLayoutParams(new ImageSwitcher.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.MATCH_PARENT
                ));
                return imageView;
            }
        });
        imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,
                android.support.design.R.anim.abc_fade_in));
        imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,
                android.support.design.R.anim.abc_fade_out));*/

        pictureLinearLayout = (LinearLayout) findViewById(R.id.pictureListLinearLayout);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);

        if (isSwitchServiceRunning()) {
            MenuItem toggleSwitchServiceMenuItem =
                    menu.findItem(R.id.action_toggle_switch_service);
            toggleSwitchServiceMenuItem.setChecked(true);
        }

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        switch (id) {
            case R.id.action_settings:
                return true;
            case R.id.action_toggle_switch_service:
                if (item.isChecked()) {
                    stopSwitchService();
                } else {
                    startSwitchService();
                }
                item.setChecked(!item.isChecked());
                return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onCreateList(String name) {

    }

    @Override
    public void onRenameList(String oldName, String newName) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (REQUEST_CODE_SELECT_PICTURE == requestCode && RESULT_OK == resultCode) {
            Uri uri = data.getData();
            String filePath = UriParser.getPath(this, uri);

            Log.d(LOG_TAG, "Selected file: " + filePath);

            String copiedFilePath = copyImageFile(filePath);
            addImageView(copiedFilePath);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_CODE_PERMISSION_WRITE_EXTERNAL_STORAGE: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    startAddPictureActivity();
                } else {
                    showToast(getString(R.string.msg_no_storage_permission));
                }
                return;
            }
        }
    }

    private void showToast(CharSequence text) {
        Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
    }

    private void closeResource(Closeable resource, String errorMessage) {
        if (resource != null) {
            try {
                resource.close();
            } catch (IOException ex) {
                Log.e(LOG_TAG, errorMessage, ex);
            }
        }
    }

    private void startSwitchService() {
        Intent intent = new Intent(this, SwitchWallpaperService.class);
        startService(intent);
    }

    private void stopSwitchService() {
        Intent intent = new Intent(this, SwitchWallpaperService.class);
        stopService(intent);
    }

    private boolean isSwitchServiceRunning() {
        return ServiceUtil.isServiceRunning(this,
                SwitchWallpaperService.class.getName());
    }

    private void addPicture() {
        boolean needRuntimePermission = false;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                needRuntimePermission = true;
                if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    showToast(getString(R.string.msg_explain_storage_permission));
                } else {
                    ActivityCompat.requestPermissions(this,
                            new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            REQUEST_CODE_PERMISSION_WRITE_EXTERNAL_STORAGE);
                }
            }
        }
        if (!needRuntimePermission) {
            startAddPictureActivity();
        }
    }

    private void startAddPictureActivity() {
        /* Start choose file activity. */
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType(CHOOSE_FILE_TYPE);
        intent.addCategory(Intent.CATEGORY_OPENABLE);

        try {
            startActivityForResult(Intent.createChooser(intent,
                    getString(R.string.action_add_picture)), REQUEST_CODE_SELECT_PICTURE);
        } catch (ActivityNotFoundException ex) {
            showToast(getString(R.string.msg_no_file_manager_found));
        }
    }

    private void addPictureList() {

    }

    @Nullable
    private String copyImageFile(@NonNull  String filePath) {
        File pictureListDirectory = FileUtil.findPictureListDirectory(DEFAULT_LIST_NAME);
        if (!pictureListDirectory.exists()) {
            pictureListDirectory.mkdirs();
        }

        File srcImageFile = new File(filePath);
        String imageFileName = srcImageFile.getName();
        File copiedImageFile = new File(pictureListDirectory, imageFileName);
        if (copiedImageFile.exists()) {
            copiedImageFile.delete();
        }

        FileInputStream input = null;
        FileOutputStream output = null;
        try {
            copiedImageFile.createNewFile();
            output = new FileOutputStream(copiedImageFile);
            input = new FileInputStream(srcImageFile);
            byte[] buffer = new byte[COPY_FILE_BUFFER_LENGTH];
            int readLength = 0;
            while ((readLength = input.read(buffer)) > 0) {
                Log.d(LOG_TAG, "Read file bytes: " + readLength);
                output.write(buffer, 0, readLength);
            }
            output.flush();
        } catch (IOException ex) {
            Log.e(LOG_TAG, "Copy image file failed.", ex);
            showToast(getString(R.string.msg_add_picture_failed));
            return null;
        } finally {
            closeResource(output, "Close image file stream failed.");
            closeResource(input, "Close image file stream failed.");
        }

        return copiedImageFile.getAbsolutePath();
    }

    private void addImageView(String filePath) {
        Drawable image = Drawable.createFromPath(filePath);

        ImageView imageView = new ImageView(this);
        imageView.setImageDrawable(image);
        pictureLinearLayout.addView(imageView);

        //imageSwitcher.setImageDrawable(image);
    }

//    @Override
//    public boolean onTouch(View v, MotionEvent event) {
//        switch (event.getAction()) {
//            case MotionEvent.ACTION_DOWN:{
//                //手指按下的X坐标
//                downX = event.getX();
//                break;
//            }
//            case MotionEvent.ACTION_UP:{
//                float lastX = event.getX();
//                //抬起的时候的X坐标大于按下的时候就显示上一张图片
//                if(lastX > downX){
//                    if(currentPosition > 0){
//                        //设置动画，这里的动画比较简单，不明白的去网上看看相关内容
//                        imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(getApplication(), R.anim.left_in));
//                        imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(getApplication(), R.anim.right_out));
//                        currentPosition --;
//                        imageSwitcher.setImageResource(imgIds[currentPosition % imgIds.length]);
//                        imageBackground(currentPosition);
//                    }else{
//                        Toast.makeText(getApplication(), "已经是第一张", Toast.LENGTH_SHORT).show();
//                    }
//                }
//
//                if(lastX < downX){
//                    if(currentPosition < imgIds.length - 1){
//                        imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(getApplication(), R.anim.right_in));
//                        imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(getApplication(), R.anim.lift_out));
//                        currentPosition ++ ;
//                        imageSwitcher.setImageResource(imgIds[currentPosition]);
//                        setImageBackground(currentPosition);
//                    }else{
//                        Toast.makeText(getApplication(), "到了最后一张", Toast.LENGTH_SHORT).show();
//                    }
//                }
//            }
//
//            break;
//        }
//
//        return true;
//    }
}
